class Solution:
    def generateMatrix(self, n):
        matrix = [[0]*n for _ in range(n)]
        num, left, right, top, bottom = 1, 0, n-1, 0, n-1
        while left <= right and top <= bottom:
            # 从左到右
            for i in range(left, right+1):
                matrix[top][i] = num
                num += 1
            top += 1
            # 从上到下
            for j in range(top, bottom+1):
                matrix[j][right] = num
                num += 1
            right -= 1
            # 
            if left <= right:
                # 从右到左
                for i in range(right, left-1, -1):
                    matrix[bottom][i] = num
                    num += 1
                bottom -= 1
            if top <= bottom:
                # 从下到上
                for j in range(bottom, top-1, -1):
                    matrix[j][left] = num
                    num += 1
                left += 1
        return matrix
             
if __name__ == '__main__':
    s = Solution()
    print(s.generateMatrix(3))